package com.sanqing.dao;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.sanqing.hibernate.HibernateSessionFactory;
import com.sanqing.po.Student;
import com.sanqing.po.Subject;
import com.sanqing.util.Page;

public class StudentDAOImpl implements StudentDAO{
	
	public Student findByStudentID(String studentID) {
		Session session = HibernateSessionFactory.getSession();//
		Student student = (Student) session.get(Student.class, studentID);
		HibernateSessionFactory.closeSession();//
		return student;
	}

	public void updateStudent(Student student) {
		Session session = HibernateSessionFactory.getSession();//
		Transaction  transaction = null;
		try{
			transaction = session.beginTransaction();
			session.update(student);//
			transaction.commit();//
		}catch(Exception ex) {
			ex.printStackTrace();
			transaction.rollback();//
		}
		HibernateSessionFactory.closeSession();
	}

	public List<Student> findByStudentName(String studentName) {
		Session session = HibernateSessionFactory.getSession();
		Query query = session.createQuery("from Student as stu where stu.studentName = ?");
		query.setString(0, studentName);
		List list = query.list();					//
		HibernateSessionFactory.closeSession();		//
		return list;
	}

	public List<Student> findByStudentClass(String sclass) {
		Session session = HibernateSessionFactory.getSession();
		Query query = session.createQuery("from Student as stu where stu.sclass = ?");
		query.setString(0, sclass);
		List list = query.list();					//
		HibernateSessionFactory.closeSession();		
		return list;
	}

	@Override
	public List<Student> findAllStudents() {
		Session session=HibernateSessionFactory.getSession();
		Query query=session.createQuery("from Student");
		List<Student> list=query.list();
		HibernateSessionFactory.closeSession();
		return list;
	}

	@Override
	public int findStudentCount() {
		Session session=HibernateSessionFactory.getSession();
		Query query=session.createQuery("from Student");
		List<Student> list =query.list();
		int count=list.size();
		return count;
	}

	@Override
	public List<Student> findStudentByPage(Page page) {
		Session session=HibernateSessionFactory.getSession();
		Query query=session.createQuery("from Student");
		query.setMaxResults(page.getEveryPage());
		query.setFirstResult(page.getBeginIndex());
		List<Student> list=query.list();	
		HibernateSessionFactory.closeSession();
		return list;
	}

	@Override
	public List<Student> likeQueryStudentByName(String name, Page page) {
		Session session=HibernateSessionFactory.getSession();
		String sql="from Student as stu where stu.studentName like %"+name+"%";
		System.out.println(sql);
		Query query=session.createQuery(sql);
		query.setMaxResults(page.getEveryPage());
		query.setFirstResult(page.getBeginIndex());
		List<Student> list=query.list();
		HibernateSessionFactory.closeSession();
		return list;
	}
	
	
	
}
